/* 动态血糖js处理 ⬇*/


//图表标题点击收起/展开
var url = location.origin;
var DBGMain = $("#DBGMain");
var DBG = $("#DBG");
var ulRecord = $(".record");
var lis = ulRecord.find("li");
var ajaxArr = [];

//最新血糖数据、日间同比血糖、高低血糖百分比 数据
var dataThree = {};
// data.dateGlucose=[];
var DBGOBJ = {
    init: function () {
        // 血糖图谱中的佩戴记录列表数据注入⬇️
        if (!dataAjaxState) {
            ajax('get', url + '/dynamic/samWear/getListByUser', {user_id: $("#user_id").val()}, getListByUserCallback);
            this.control()
        }
    },
    control: function () {
        $("#RBGModel .RGBCave").bind('click', function () {

            obj = {
                collectedtime: $(".textbox-text").val(),
                value: $("#RBGVal").val(),
                user_id: $("#user_id").val(),
            };
            if (obj.collectedtime == "") {
                alertModel('温馨提示', '时间不能为空！')
            } else if (obj.value == "") {
                alertModel("温馨提示", '参比血糖值不能为空！')
            } else {
                setTimeout(function () {
                    ajax('post', url + '/dynamic/samReferGlucose', obj, function (data) {
                        if (data.code !== 10000) {
                            alertModel("温馨提示", data.message)
                        } else {
                            $("#RBGModel").fadeOut("normal");
                        }
                    })
                }, 50);

            }
        });
        $("#RBGVal").blur(function () {
            $("#RBGVal").val(checkMInMax($("#RBGVal").val(), 1, 50, 1));
        })

    },

    // 佩戴记录时间绑定⬇️
    getListBind: function () {
        //获取li的总个数，然后计算ul的总宽度；
        ulRecord.width($(".record").find("li").length * lis.width());
        //为佩戴记录的li绑定切换样式事件，已经获取新的数据；
        lis.unbind().click(function () {
            $(this).siblings("li").removeClass("hasBorder").end().addClass("hasBorder");
            obj = {
                // startTime: $(this).find("b.sTime").html(),
                // endTime: $(this).find("b.eTime").html(),
                user_id: $("#user_id").val(),
                id: $(this).attr("data-id")
            };
            // obj={
            //     start:'2018-04-01 14:33:00',
            //     end:'2018-04-20 14:51:00',
            //     user_id:14888,
            // };
            // ajax('get', url + '/dynamic/samGlucose/getListByUser', obj, chartsCallBack);
            ajaxArr.push($(this).attr('data-sensorcode'));
            DBGOBJ.getThreeData(obj);//连续，日间，高低  交互方法调用
            DBGOBJ.getDietData(obj);//饮食 交互调用
            DBGOBJ.getInsulinData(obj);//胰岛素 交互调用

        });
        lis.eq(0).click();
    },
    getThreeData: function (obj) {
        if (ajaxArr[ajaxArr.length - 1] !== ajaxArr[ajaxArr.length - 2]) {
            ajax('get', url + '/dynamic/getDynamicBloodGlucose', obj, chartsCallBack);
        }
    },
    getDietData: function (obj) {
        if (ajaxArr[ajaxArr.length - 1] !== ajaxArr[ajaxArr.length - 2]) {
            ajax('get', url + '/dynamic/bloodDiet/eatTangValue', obj, chartsCallBack1);

        }
    },
    getInsulinData: function (obj) {
        if (ajaxArr[ajaxArr.length - 1] !== ajaxArr[ajaxArr.length - 2]) {
            ajax('get', url + '/dynamic/bloodMedication/sportTangValue', obj, chartsCallBack2);

        }
    }

};


function getListByUserCallback(data) {
    if (data.code == 10000) {
        var wearHtml = '';
        $.each(data.data, function (k, v) {
            if (v.starttime) {
                var sTime = v.starttime.slice(0, 10);
            } else {
                sTime = "";
            }
            if (v.endtime) {
                var eTime = v.endtime.slice(0, 10);
            } else {
                eTime = "";
            }


            wearHtml += '<li data-id="' + v.id + '" data-sensorcode="' + v.id + '" class="">' +
                '<div>' +
                '<span>时间：</span>' +
                '<b class="sTime">' + sTime + '</b>' +
                '<span>至</span>' +
                '<b class="eTime">' + eTime + '</b>' +
                '</div>' +
                '<div><span>发射器编号：</span><b>' + checkUndefined(v.emittercode) + '</b></div>' +
                '</li>'
        });
        $("#DBGMain").find("ul.record").html(wearHtml);
        // $("#DBGMain ul.record li").first().addClass('hasBorder');
        lis = ulRecord.find("li");
        DBGOBJ.getListBind();

    } else if (data.code == 40001) {
        // alertModel("温馨提示", '佩戴记录未查询到数据！')
        $("#DBGMain").html('<h3 style="text-align:center;padding:2px;">暂无数据</h3>')

    } else {
        alertModel("温馨提示", data.message)
    }
};


$(document).ready(function (e) {
    var cirSpan = $('span.cirSpan');
    cirSpan.click(function (e) {
        e.preventDefault();
        if ($(this).hasClass('first')) {
            if ($('.chart2-1a-table').css('display') == 'block') {
                $(".look").click();
            }
        }
        $(this).find("i").toggleClass('fold')
            .parent().siblings('div.chart2-2').stop().slideToggle(240);

    });
});


//点击查看日志显示table
DBGMain.find(".look").unbind().click(function (e) {
    e.preventDefault();
    e.stopPropagation();
    // $(this).next("div").toggle();
    if ($(this).next("div").next(".chart2-1a-table").css("display") === 'none') {
        var obj = {
            // start:'2003-10-03',
            // end:'2018-05-03',
            id: $(".record").find('.hasBorder').attr("data-id"),
            user_id: $("#user_id").val()
        };
        var html = '';
        ajax('get', url + '/dynamic/samGlucose/getListByTimeByUId', obj, function (data) {
            if (data.code == 10000) {
                $.each(data.data, function (k, v) {
                    html += '<tr data-id="' + v.id + '">' +
                        '<td>' + checkUndefined(v.collectedtime) + '</td>' +
                        '<td>' + checkUndefined(v.value) + '</td>' +
                        '<td>' + checkUndefined(v.currentvalue) + '</td>' +
                        '</tr>'
                })
                $('table#chartTable tbody').html(html)

            } else if (data.code == 40001) {
                $("#chartTable").html("<p>暂无数据</p>").css("border","none")
            } else {
                alertModel('温馨提示', data.message)
            }

        });
        $(this).next("div").hide()
    } else {
        $(this).next("div").show();

    }
    $(this).next("div").next(".chart2-1a-table").toggle();
    ($(this).html() === "查看日志") ? $(this).html("返回图表") : $(this).html("查看日志");
});
DBG.find("ul.DBGChildTab li").unbind().click(function () {
    var self = this;
    $(self).siblings("li").removeClass("active").end().addClass("active");
    // $("#DBGMain").load(this.className+'.html');
    $(".counterDiv").hide();
    $('#' + $(this).attr("data-id")).show();
    $("#RBGModel,#printModel").fadeOut("normal");
});


Highcharts.setOptions({
    lang: {
        contextButtonTitle: "图表导出菜单",
        decimalPoint: ".",
        downloadJPEG: "下载JPEG图片",
        downloadPDF: "下载PDF文件",
        downloadPNG: "下载PNG文件",
        downloadSVG: "下载SVG文件",
        drillUpText: "返回 {series.name}",
        loading: "加载中",
        months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        noData: "没有数据",
        numericSymbols: ["千", "兆", "G", "T", "P", "E"],
        printChart: "打印图表",
        resetZoom: "恢复缩放",
        resetZoomTitle: "恢复缩放",
        shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
        thousandsSep: ",",
        weekdays: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"]
    }
});


// $(function() {
//     $('.dtpicker').datetimepicker({
//         language: 'zh-CN',
//         format: 'yyyy-mm',
//         startView: 'year',
//         minView: 'year',
//         autoclose: true,
//         todayBtn: true
//     });
// });


//chart1-1 血糖双周 Start
var chart1_1 = function (data, low, high) {
    var d = [];
    var data1 = [];
    var data2 = [];
    var data3 = [];
    var data4 = [];
    var data5 = [];
    var data6 = [];
    var data7 = [];
    var data8 = [];
    $.each(data, function (k, v) {
        d.push(k);
        $.each(v, function (vk, vv) {
            if (isNaN(parseFloat(vv)) == true) {
                vv = null;
            } else {
                vv = parseFloat(vv);
            }
            switch (vk) {
                case 0:
                    data1.push(vv);
                    break;
                case 1:
                    data2.push(vv);
                    break;
                case 2:
                    data3.push(vv);
                    break;
                case 3:
                    data4.push(vv);
                    break;
                case 4:
                    data5.push(vv);
                    break;
                case 5:
                    data6.push(vv);
                    break;
                case 6:
                    data7.push(vv);
                    break;
                case 7:
                    data8.push(vv);
                    break;
            }
        });
    });
    $('#chart1-1').highcharts({
        chart: {
            type: 'line',
            zoomType: 'x'
        },
        credits: {
            enabled: false
        },
        title: {
            text: '血糖双周',
            y: 15,
            align: 'center',
            style: {
                'color': '#696969',
                'fontSize': '14px',
                'fontFamily': 'Microsoft YaHei'
            }
        },
        xAxis: {
            categories: d
        },
        yAxis: {
            title: {
                text: '血糖值 (mmol/L)'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#eaffe3'
            }, {
                from: parseFloat(low),
                to: parseFloat(high),
                color: 'rgba(245, 247, 250, 1)',
            }
            ]
        },
        tooltip: {
            valueSuffix: 'mmol/L'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'bottom',
            borderWidth: 0
        },
        plotOptions: {
            series: {
                connectNulls: true,
                marker: {
                    radius: 3, //曲线点半径，默认是4
                    symbol: 'circle' //曲线点类型："circle", "square", "diamond", "triangle","triangle-down"，默认是"circle"
                }
            }
        },

        series: [{
            name: '凌晨',
            color: '#39dedc',
            data: data1
        }, {
            name: '早餐前',
            color: '#673def',
            data: data2
        }, {
            name: '早餐后',
            color: '#57da34',
            data: data3
        }, {
            name: '午餐前',
            color: '#3368ed',
            data: data4
        }, {
            name: '午餐后',
            color: '#edbf33',
            data: data5
        }, {
            name: '晚餐前',
            color: '#ff4c4c',
            data: data6
        }, {
            name: '晚餐后',
            color: '#e329cf',
            data: data7
        }, {
            name: '睡前',
            color: '#cc7f1a',
            data: data8
        }]
    });
};
//chart1-1 血糖双周 End


//chart1-2 血糖整月 Start
var chart1_2 = function (data, low, high) {
    var d = [];
    var data1 = [];
    var data2 = [];
    var data3 = [];
    var data4 = [];
    var data5 = [];
    var data6 = [];
    var data7 = [];
    var data8 = [];
//	  console.log(data);
    $.each(data, function (k, v) {
        d.push(k);
        $.each(v, function (vk, vv) {
            if (isNaN(parseFloat(vv)) == true) {
                vv = null;
            } else {
                vv = parseFloat(vv);
            }
            switch (vk) {
                case 0:
                    data1.push(vv);
                    break;
                case 1:
                    data2.push(vv);
                    break;
                case 2:
                    data3.push(vv);
                    break;
                case 3:
                    data4.push(vv);
                    break;
                case 4:
                    data5.push(vv);
                    break;
                case 5:
                    data6.push(vv);
                    break;
                case 6:
                    data7.push(vv);
                    break;
                case 7:
                    data8.push(vv);
                    break;
            }
        });
    });

    $('#chart1-2').highcharts({
        chart: {
            type: 'line',
            zoomType: 'x'
        },
        credits: {
            enabled: false
        },
        title: {
            text: '血糖整月',
            y: 15,
            align: 'center',
            style: {
                'color': '#696969',
                'fontSize': '14px',
                'fontFamily': 'Microsoft YaHei'
            }
        },
        xAxis: {
            categories: d
        },
        yAxis: {
            title: {
                text: '血糖值 (mmol/L)'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#eaffe3'
            }, {
                from: parseFloat(low),
                to: parseFloat(high),
                color: 'rgba(245, 247, 250, 1)',
            }]
        },
        tooltip: {
            valueSuffix: 'mmol/L'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'bottom',
            borderWidth: 0
        },
        plotOptions: {
            series: {
                connectNulls: true,
                marker: {
                    radius: 3, //曲线点半径，默认是4
                    symbol: 'circle' //曲线点类型："circle", "square", "diamond", "triangle","triangle-down"，默认是"circle"
                }
            }
        },

        series: [{
            name: '凌晨',
            color: '#39dedc',
            data: data1
        }, {
            name: '早餐前',
            color: '#673def',
            data: data2
        }, {
            name: '早餐后',
            color: '#57da34',
            data: data3
        }, {
            name: '午餐前',
            color: '#3368ed',
            data: data4
        }, {
            name: '午餐后',
            color: '#edbf33',
            data: data5
        }, {
            name: '晚餐前',
            color: '#ff4c4c',
            data: data6
        }, {
            name: '晚餐后',
            color: '#e329cf',
            data: data7
        }, {
            name: '睡前',
            color: '#cc7f1a',
            data: data8
        }]
    });
};
//chart1-2 血糖整月 End


//所有图表的调用⬇️,


//chart2-2a 连续图谱 Start
var chart2_2a = function (data, minTime, maxTime, username, referList, medicalInfo1, medicalInfo2, diet, motion) {
    minTime -= 7200000;
    maxTime += 7200000;
    Highcharts.setOptions({
        lang: {
            months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月',
                '8月', '9月', '10月', '11月', '12月'],
            shortMonths: ['1月', '2月', '3月', '4月', '5月', '6月', '7月',
                '8月', '9月', '10月', '11月', '12月'],
            weekdays: ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        }
    });
    $('#chart2-2a').highcharts({
        chart: {
            renderTo: 'container',
            type: 'spline',
            spacingTop: 0,
            spacingRight: 100,
            spacingBottom: 0,
            spacingLeft: 0
        },
        credits: {
            enabled: false
        },
        global: {
            useUTC: true
        },
        title: {
            text: username + '：最新血糖数据'
        },
        xAxis: {
            type: 'datetime',//标志时间
            min: minTime,
            max: maxTime,
            dateTimeLabelFormats: {
                second: '%Y-%m-%d<br/>%H:%M:%S',
                minute: '%H:%M',
                hour: '%H:%M',
                day: '%Y<br/>%m-%d',
                week: '%Y<br/>%m-%d',
                month: '%Y-%m',
                year: '%Y'
            }
            //categories: ['00:00<br>2016-05-21', '08:00', '16:00', '00:00<br>2016-05-22', '08:00', '16:00', '00:00<br>2016-05-23', '08:00', '16:00', '00:00<br>2016-05-24', '08:00', '16:00', '00:00<br>2016-05-25', '08:00', '16:00', '00:00<br>2016-05-26', '08:00', '16:00', '00:00<br>2016-05-27', '08:00', '16:00']
        },
        yAxis: {
            min: 0,
            max: 25,
            showEmpty: false,
            title: {
                text: 'mmol/L'//纵轴标题
            },
            lineWidth: 1,
            //颜色划分区域
            plotBands: [{ // 高血糖
                from: 11.1,
                to: 25,
                color: 'rgba(168, 211, 236, 1)'
            }, { // 正常
                from: 7.8,
                to: 11.1,
                color: 'rgba(0, 0, 0, 0)'
            }, { // 正常
                from: 7.0,
                to: 7.8,
                color: 'rgba(0, 0, 0, 0)'
            }, { // 低血糖
                from: 5.6,
                to: 7.0,
                color: 'rgba(254, 246, 202,1)'
            }, { // 低血糖
                from: 3.9,
                to: 5.6,
                color: 'rgba(255, 238, 165, 1)'
            }, { // 低血糖
                from: 1.7,
                to: 3.9,
                color: 'rgba(255, 211, 145, 1)'
            }, { // 低血糖
                from: 0,
                to: 1.7,
                color: 'rgba(254, 177, 121, 1)'
            }]
        },

        tooltip: {
            enabled: true,
            dateTimeLabelFormats: {
                millisecond: '%A, %b %e, %H:%M:%S.%L',
                second: '%A, %b %e, %H:%M:%S',
                minute: '%A, %b %e, %H:%M',
                hour: '%A, %b %e, %H:%M',
                day: '%A, %b %e, %Y',
                week: 'Week from %A, %b %e, %Y',
                month: '%B %Y',
                year: '%Y'
            },
            headerFormat: '<span style="font-size: 12px">{point.key}</span><br/>',
            pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>mmol/L<br/>',
            xDateFormat: '%Y-%m-%d %H:%M'
        },
        legend: {
            layout: 'horizontal',
            align: 'center',
            verticalAlign: 'bottom',
            borderWidth: 1,
            borderColor: '#CCC'
        },
        plotOptions: {
            series: {
                marker: {
                    radius: 5, //曲线点半径，默认是4
                    symbol: 'circle' //曲线点类型："circle", "square", "diamond", "triangle","triangle-down"，默认是"circle"
                }
            },
            scatter: {
                tooltip: {
                    headerFormat: '<span style="font-size: 12px">{point.key}</span><br/>',
                    pointFormat: '<span style="color:{series.color}">{series.name}<br/><br/></span><b>{point.attr}</b><br/>',
                    xDateFormat: '%Y-%m-%d %H:%M'
                }
            }
        },


        series: [{//血糖数据
            name: '血糖值',
            data: data,
            marker: {
                enabled: false,
                states: {
                    hover: {
                        enabled: true
                    }
                },
            },
            states: {
                hover: {lineWidth: 2}
            },
            color: '#4572A7',
            lineWidth: 1.5
        }, {
            type: 'scatter',
            name: '参比血糖',
            color: '#FF4949',
            data: referList,
            marker: {radius: 4}
//	  id:'refer',
//      type: 'scatter',
//      name: '参比',//'BG',http://bj.jjj.qq.com/a/20160816/016851.htm
//      data: referList,//参比赋值
//      marker: {radius: 5,symbol:'circle'}
        }, {
            type: 'scatter',
            name: '注射胰岛素',
            color: '#F07BDD',
            data: medicalInfo1,
            marker: {radius: 4, symbol: 'triangle'}
        }, {
            type: 'scatter',
            name: '用药',
            color: '#2ED7B8',
            data: medicalInfo2,
            marker: {radius: 4, symbol: 'square'}
        }, {
            type: 'scatter',
            name: '运动',
            color: '#F4B64C',
            data: motion,
            marker: {radius: 4, symbol: 'triangle-down'}
        }, {
            type: 'scatter',
            name: '饮食',
            color: '#B699EB',
            data: diet,
            marker: {radius: 4, symbol: 'diamond'}
        }]
    });
};
//chart2-2a 连续图谱 End




